
#include "stdafx.h"
#include "../client/DCPlusPlus.h"
#include "Resource.h"

#include "ClientVersionFrame.h"
#include "ClientVersionDlg.h"
#include "WinUtil.h"

int ClientVersionFrame::columnIndexes[] = { COLUMN_CLIENT_NAME, COLUMN_LAST_VERSION, COLUMN_CURRENT_VERSION,
COLUMN_COMMENT, COLUMN_ADDRESS, COLUMN_CLIENT_ADDRESS, COLUMN_UPDATE_TIME, COLUMN_ALERT, COLUMN_UPDATED };
int ClientVersionFrame::columnSizes[] = { 120, 90, 90, 90, 90, 90, 90, 90, 90};
static ResourceManager::Strings columnNames[] = { 
	ResourceManager::CLIENT, 
	ResourceManager::LAST_VERSION, 
	ResourceManager::CURRENT_VERSION, 
	ResourceManager::COMMENT,
	ResourceManager::ADDRESS, 
	ResourceManager::CLIENT_ADDRESS, 
	ResourceManager::TIME_OF_UPDATE,
	ResourceManager::ALERT,
	ResourceManager::UPDATED
};

// Frame creation
LRESULT ClientVersionFrame::onCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
	// Create status bar
	CreateSimpleStatusBar(ATL_IDS_IDLEMESSAGE, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | SBARS_SIZEGRIP);
	ctrlStatus.Attach(m_hWndStatusBar);
	// Create list control
	ctrlVersions.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | 
		WS_HSCROLL | WS_VSCROLL | LVS_REPORT | LVS_SHOWSELALWAYS, WS_EX_CLIENTEDGE, IDC_C_VER_LIST);
	// Ev. set full row select
	if(BOOLSETTING(FULL_ROW_SELECT)) {
		ctrlVersions.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP);
	} else {
		ctrlVersions.SetExtendedListViewStyle(LVS_EX_HEADERDRAGDROP);
	}

//	 Set background color
	ctrlVersions.SetBkColor(WinUtil::bgColor);
	ctrlVersions.SetTextBkColor(WinUtil::bgColor);
	ctrlVersions.SetTextColor(WinUtil::textColor);

	// Create listview columns
	WinUtil::splitTokens(columnIndexes, SETTING(CV_FRAME_ORDER), COLUMN_LAST);
	WinUtil::splitTokens(columnSizes, SETTING(CV_FRAME_WIDTHS), COLUMN_LAST);

	for(int j = 0; j < COLUMN_LAST; j++) 
	{
		int fmt = LVCFMT_LEFT;
		ctrlVersions.InsertColumn(j, CTSTRING_I(columnNames[j]), fmt, columnSizes[j], j);
	}
	ctrlVersions.SetColumnOrderArray(COLUMN_LAST, columnIndexes);

	// Create buttons
	ctrlAdd.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
		BS_PUSHBUTTON , 0, IDC_ADD);
	ctrlAdd.SetWindowText(CTSTRING(NEW));
	ctrlAdd.SetFont(WinUtil::font);

	ctrlEdit.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
		BS_PUSHBUTTON , 0, IDC_EDIT);
	ctrlEdit.SetWindowText(CTSTRING(PROPERTIES));
	ctrlEdit.SetFont(WinUtil::font);

	ctrlRemove.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
		BS_PUSHBUTTON , 0, IDC_REMOVE);
	ctrlRemove.SetWindowText(CTSTRING(REMOVE));
	ctrlRemove.SetFont(WinUtil::font);

	ctrlOpenXml.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
		BS_PUSHBUTTON , 0, IDC_XML);
	ctrlOpenXml.SetWindowText(CTSTRING(OPEN_VERSION));
	ctrlOpenXml.SetFont(WinUtil::font);

	ctrlOpenSite.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
		BS_PUSHBUTTON , 0, IDC_SITE);
	ctrlOpenSite.SetWindowText(CTSTRING(OPEN_SITE));
	ctrlOpenSite.SetFont(WinUtil::font);

	ctrlCheckVersion.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
		BS_PUSHBUTTON , 0, IDC_UPDATE_CHECK);
	ctrlCheckVersion.SetWindowText(CTSTRING(UPDATE_CHECK));
	ctrlCheckVersion.SetFont(WinUtil::font);

	ctrlReload.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
		BS_PUSHBUTTON , 0, IDC_RELOAD_CLIENTS);
	ctrlReload.SetWindowText(CTSTRING(RELOAD));
	ctrlReload.SetFont(WinUtil::font);
	
	ClientVersion::List lst = ClientVersionManager::getInstance()->getClientVersions(false);

	for(ClientVersion::Iter i = lst.begin(); i != lst.end(); ++i) {
		ClientVersion& cv = *i;	
		addEntry(cv, ctrlVersions.GetItemCount());
	}

	m_hMenu = WinUtil::mainMenu;

	bHandled = FALSE;
	return TRUE;
}

// Close window
LRESULT ClientVersionFrame::onClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) 
{
	if(!closed){
	ClientVersionManager::getInstance()->saveClientList();
	WinUtil::saveHeaderOrder(ctrlVersions, SettingsManager::CV_FRAME_ORDER, 
		SettingsManager::CV_FRAME_WIDTHS, COLUMN_LAST, columnIndexes, columnSizes);

	bHandled = FALSE;
	closed = true;
	PostMessage(WM_CLOSE);
	}else{
		MDIDestroy(m_hWnd);
	}
	return 0;
}

// Recalculate frame control layout
void ClientVersionFrame::UpdateLayout(BOOL bResizeBars /* = TRUE */) 
{
	RECT rect;
	GetClientRect(&rect);

	// Position bars and offset their dimensions
	UpdateBarsPosition(rect, bResizeBars);
	if(ctrlStatus.IsWindow()) 
	{
		CRect sr;
		int w[1];
		ctrlStatus.GetClientRect(sr);

		w[0] = sr.Width();
		ctrlStatus.SetParts(1, w);
	}

	// Position list control
	CRect rc = rect;
	rc.top += 2;
	rc.bottom -= 28;
	ctrlVersions.MoveWindow(rc);

	// Position buttons
	const long bwidth = 90;
	rc = rect;
	rc.bottom -= 2;
	rc.top = rc.bottom - 22;

	rc.left = 2;
	rc.right = rc.left + bwidth;
	ctrlAdd.MoveWindow(rc);

	rc.left += bwidth + 2;
	rc.right = rc.left + bwidth;
	ctrlEdit.MoveWindow(rc);

	rc.left += bwidth + 2;
	rc.right = rc.left + bwidth;
	ctrlRemove.MoveWindow(rc);
	
	rc.left += 20;

	rc.left += bwidth + 2;
	rc.right = rc.left + bwidth;
	ctrlOpenXml.MoveWindow(rc);

	rc.left += bwidth + 2;
	rc.right = rc.left + bwidth;
	ctrlOpenSite.MoveWindow(rc);
	
	rc.left += 20;

	rc.left += bwidth + 2;
	rc.right = rc.left + bwidth;
	ctrlCheckVersion.MoveWindow(rc);

	rc.left += 20;

	rc.left += bwidth + 2;
	rc.right = rc.left + bwidth;
	ctrlReload.MoveWindow(rc);


}
void ClientVersionFrame::addEntry(const ClientVersion& cv, int pos) {
	StringList lst;

	lst.push_back(cv.getClientName());
	lst.push_back(cv.getLastVersion());
	lst.push_back(cv.getCurrentVersion());
	lst.push_back(cv.getComment());
	lst.push_back(cv.getAddress());
	lst.push_back(cv.getClientAddress());
	lst.push_back(cv.getUpdateTime());
	lst.push_back(WinUtil::toYesNo(Util::toBool(cv.getAlert())));
	lst.push_back(WinUtil::toYesNo(Util::toBool(cv.getUpdated())));
	
	ctrlVersions.insert(pos, lst, 0, (LPARAM)cv.getId());
}

LRESULT ClientVersionFrame::onAddClient(WORD , WORD , HWND , BOOL& ) {
	ClientVersionDlg dlg;
	dlg.currentVersionId = -1;

	if(dlg.DoModal() == IDOK) {
		addEntry(ClientVersionManager::getInstance()->addClientVersion(
			dlg.clientName, 
			dlg.lastVersion, 
			dlg.currentVersion, 
			dlg.comment, 
			dlg.address, 
			dlg.clientAddress,
			dlg.updateTime,
			dlg.alert,
			dlg.updated
			), ctrlVersions.GetItemCount());
		
	}
	return 0;
}
LRESULT ClientVersionFrame::onChangeClient(WORD , WORD , HWND , BOOL& ) {
	if(ctrlVersions.GetSelectedCount() == 1) {
		int sel = ctrlVersions.GetNextItem(-1, LVNI_SELECTED);
		
		ClientVersionDlg dlg;

		dlg.currentVersionId = ctrlVersions.GetItemData(sel);

		if(dlg.DoModal() == IDOK) {
			dlg.currentVersionProfile.setClientName(dlg.clientName);
			dlg.currentVersionProfile.setLastVersion(dlg.lastVersion);
			dlg.currentVersionProfile.setCurrentVersion(dlg.currentVersion);
			dlg.currentVersionProfile.setComment(dlg.comment);
			dlg.currentVersionProfile.setAddress(dlg.address);
			dlg.currentVersionProfile.setClientAddress(dlg.clientAddress);
			dlg.currentVersionProfile.setUpdateTime(dlg.updateTime);
			dlg.currentVersionProfile.setAlert(dlg.alert);
			dlg.currentVersionProfile.setUpdated(dlg.updated);

			ClientVersionManager::getInstance()->updateClientVersion(dlg.currentVersionProfile);
		}
		update();
		ctrlVersions.EnsureVisible(sel, FALSE);
		ctrlVersions.SetRedraw(TRUE);
	}
	return 0;
}
LRESULT ClientVersionFrame::onRemoveClient(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) {
	
	if(MessageBox(_T("Are you sure you want to remove the selected item?"), _T("Remove?"), MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) == IDYES) {
		if(ctrlVersions.GetSelectedCount() == 1) {
			int i = ctrlVersions.GetNextItem(-1, LVNI_SELECTED);
			ClientVersionManager::getInstance()->removeClientVersion(ctrlVersions.GetItemData(i));
			ctrlVersions.DeleteItem(i);
		}
	}
	return 0;
}
void ClientVersionFrame::on(VersionManagerListener::Types type) throw() {
	if( type == VersionManagerListener::LIST_UPDATED){
		update();
		setTabColor(RGB(0, 0, 255));
	}
}
//Sulan start svn5?
void ClientVersionFrame::update(){
		ctrlVersions.SetRedraw(FALSE);
		ctrlVersions.DeleteAllItems();
		ClientVersion::List lst = ClientVersionManager::getInstance()->getClientVersions();
		for(ClientVersion::Iter j = lst.begin(); j != lst.end(); ++j) {
			ClientVersion& cp = *j;	
			addEntry(cp, ctrlVersions.GetItemCount());
		}
		ctrlVersions.SetRedraw(TRUE);
		addLine("List updated");
}
//End
LRESULT ClientVersionFrame::onCustomDraw(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/) {
	LPNMLVCUSTOMDRAW cd = (LPNMLVCUSTOMDRAW)pnmh;

	switch(cd->nmcd.dwDrawStage) {
	case CDDS_PREPAINT:
		return CDRF_NOTIFYITEMDRAW;

	case CDDS_ITEMPREPAINT:
		{
			try	{
				ClientVersion cp;
				ClientVersionManager::getInstance()->getClientVersion(ctrlVersions.GetItemData(cd->nmcd.dwItemSpec), cp);
				if (cp.getUpdated()) {
					cd->clrText = RGB(0,0,250);
					cd->clrTextBk = RGB(250,250,250);
				}else if(cp.getCurrentVersion().empty()){
					cd->clrText = RGB(200,0,0);
					cd->clrTextBk = RGB(250,250,250);
				}else{
					cd->clrText = RGB(0,128,64);
					cd->clrTextBk = RGB(230,230,230);
				}
				return CDRF_NEWFONT | CDRF_NOTIFYSUBITEMDRAW;
			}
			catch(const Exception&)
			{
			}
			catch(...) 
			{
			}
		}
		return CDRF_NOTIFYSUBITEMDRAW;

	default:
		return CDRF_DODEFAULT;
	}
}
LRESULT ClientVersionFrame::onContextMenu(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled) {
	// client area of window
	RECT rc;
	// location of mouse click
	POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };

	ctrlVersions.GetClientRect(&rc);
	ctrlVersions.ScreenToClient(&pt); 

	if (PtInRect(&rc, pt)) {
		ctrlVersions.ClientToScreen(&pt);
		CMenu menu;
		menu.CreatePopupMenu();
		menu.AppendMenu(MF_STRING, IDC_ADD, CTSTRING(NEW));
		if(ctrlVersions.GetSelectedCount() > 0) {
			menu.AppendMenu(MF_STRING, IDC_EDIT, CTSTRING(PROPERTIES));
			
			menu.AppendMenu(MF_STRING, IDC_REMOVE, CTSTRING(REMOVE));
			menu.AppendMenu(MF_SEPARATOR);
			menu.AppendMenu(MF_STRING, IDC_SITE, CTSTRING(OPEN_SITE));
			menu.AppendMenu(MF_STRING, IDC_XML, CTSTRING(OPEN_VERSION));
			menu.AppendMenu(MF_SEPARATOR);
			menu.AppendMenu(MF_STRING, IDC_UPDATE_CHECK, CTSTRING(UPDATE_CHECK));
		}
		menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, m_hWnd);
		return TRUE; 
	}
	bHandled = FALSE;
	return FALSE;
}


LRESULT ClientVersionFrame::onContextAction(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) {
	if(ctrlVersions.GetSelectedCount() == 1) {
		int i = ctrlVersions.GetNextItem(-1, LVNI_SELECTED);
		ClientVersionManager::getInstance()->getClientVersion(ctrlVersions.GetItemData(i), currentVersionProfile);
		switch(wID){
			case IDC_UPDATE_CHECK: ClientVersionManager::getInstance()->checkClient(currentVersionProfile.getAddress());break;
			case IDC_SITE: WinUtil::openLink(currentVersionProfile.getClientAddress());break;
			case IDC_XML: WinUtil::openLink(currentVersionProfile.getAddress());break;
		
		}
	}
	return 0;
}
//End
/**
 File End
 */